package cn.zymall.app.service.impl;

import cn.zymall.app.service.MenuService;
import cn.zymall.common.model.IndexMenu;
import cn.zymall.common.utils.redis.RedisFieldItem;
import cn.zymall.common.utils.redis.RedisUtil;
import cn.zymall.common.utils.response.HttpResult;
import cn.zymall.common.utils.time.TimeUtil;
import com.aliyun.oss.common.utils.DateUtil;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author xuxianda
 * @Description: 菜单业务层接口实现类
 * @date 2020/8/26 11:55
 * @Copyright
 * @return
 **/
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    TimeUtil timeUtil;

    @Autowired
    Gson gson;

    @Override
    public HttpResult save(IndexMenu indexMenu) {
        try {
            indexMenu.setCreateTime(timeUtil.getSystemDateSring());
            String mStr = gson.toJson(indexMenu);
            RedisFieldItem redisFieldItem = new RedisFieldItem();
            redisFieldItem.setMenuKey(indexMenu.getMenuId());
            redisFieldItem.setMenuValue(mStr);
            if (redisUtil.set(redisFieldItem.getMenuKey(), redisFieldItem.getMenuValue())) {
                return new HttpResult().success("添加菜单成功");
            }
            return new HttpResult().fail("添加菜单失败");
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult().fail("系统错误");
        }
    }

    @Override
    public HttpResult remove(IndexMenu indexMenu) {
        return null;
    }

    @Override
    public HttpResult query() {
        Set<String> keys = redisUtil.getRedisTemplate().keys("menu:*");
        List<IndexMenu> list = new ArrayList<>();
        for (String key : keys) {
            try {
                list.add(gson.fromJson((String) redisUtil.get(key), IndexMenu.class));
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
        return new HttpResult().success("查询成功", list);
    }
}
